/**
 * 
 */
package praktikumid.w09.p3;

import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Container;
import java.awt.Dimension;
import java.awt.Font;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;

import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextField;
import javax.swing.SwingConstants;

/**
 * @author Aleksandr
 *
 */
public class UserInput extends JFrame implements ActionListener, KeyListener {

	protected JTextField text;
	protected JLabel label;

	/*
	 * class constructor
	 */
	public UserInput() {
		setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		setPreferredSize(new Dimension(300,200));
		//setSize(300, 200);
		setTitle("User input");
		setVisible(true);
	}
		
	public void ConstructUI() {
		
		/*
		 * setting a BorderLayout for
		 * the content pane
		 */
		Container pane = getContentPane();
		pane.setLayout(new BorderLayout());
	
		/*
		 * upper panel contains a button
		 * and a text edit field
		 */
		JPanel upper = new JPanel();
		upper.setBackground(Color.GREEN);
		text = new JTextField(15);
		text.addKeyListener(this);
		upper.add(text);
		JButton b = new JButton("Change text");
		b.addActionListener(this);
		upper.add(b);
		
		/*
		 * lower panel contains label
		 */
		JPanel lower = new JPanel();
		lower.setBackground(Color.GRAY);
		
		label = new JLabel("Label");
		label.setBackground(Color.LIGHT_GRAY);
		label.setOpaque(true);
		label.setHorizontalAlignment(SwingConstants.CENTER);
		label.setVerticalAlignment(SwingConstants.CENTER);
		label.setFont(new Font("Arial", Font.PLAIN, 20));
		
		
		/*
		 * adding panels to content pane
		 */
		pane.add(upper, BorderLayout.PAGE_START);
		pane.add(label, BorderLayout.CENTER);
		
		/*
		 * calculate the size to fit all the contained
		 * components and validate the container and 
		 * all its subcomponents
		 * 
		 * if we have set size explicitly using the 
		 * setSize() method, we also need to explicitly 
		 * validate by calling validate();
		 */
		pack();		
	}
	
	/*
	 * Event handlers
	 * required to be added by the 
	 * ActionListener and KeyListener 
	 * interfaces
	 */
	public void actionPerformed(ActionEvent e) {
		label.setText(text.getText());
	}
	
	public void keyPressed(KeyEvent e) {}
	
	public void keyTyped(KeyEvent e) {}
	
	public void keyReleased(KeyEvent e){
		if (e.getKeyCode() == KeyEvent.VK_ENTER) {
			label.setText(text.getText());
		}
	}
	
	/**
	 * @param args pareters
	 */
	public static void main(String[] args) {
		
		/*
		 * basic JFrame initialization
		 */
		UserInput input = new UserInput();
		input.ConstructUI();
	}

}
